package com.mofang.powerdekorhelper.utils;

import android.os.Handler;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by luofei on 2017/8/18 0018.
 */

public class Countdown {

    private Timer timer = null;

    private TimerTask timerTask = null;

    private int divideTime = 1 * 1000;

    private int timeCount = 60;

    private boolean isStop = true;

    UpDataTime upDataTime;

    public void createTimer(UpDataTime IupDataTime) {

        upDataTime = IupDataTime;

        if (timer == null) {
            timer = new Timer();
        }

        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    timeCount--;
                    L.e("TimerTask", "timerTask----------->" + timeCount);

                    Message msg = new Message();
                    msg.what = timeCount;
                    handler.sendMessage(msg);
                }
            };

            start();
        }
    }

    public void setDivideTime(int divideTime) {
        this.divideTime = divideTime;
    }

    public void setTimeCount(int timeCount) {
        this.timeCount = timeCount;
    }

    public void setStop(boolean stop) {
        isStop = stop;
    }

    public void start() {
        timer.schedule(timerTask, 0, divideTime);
    }

    public void stop() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        timeCount = 60;
    }

    public interface UpDataTime {

        void updataTime(int time);

    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            upDataTime.updataTime(timeCount);

            if (timeCount == 0) {
                stop();
            }
        }
    };

}
